import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PmpSysUserEntity } from '@/pmp/entity/pmp.sys.user.entity';
import * as captcha from 'svg-captcha';
import { RedisService } from '@/common/redis/redis.service';
import { CAPTCHA_CONFIG } from '@/constants/captcha';
import { LoginDto } from '@/pmp/dto/login.dto';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
import { PassLoginDto } from '@/pmp/dto/passLogin.dto';

type LoginResponse = {
  user: PmpSysUserEntity;
  token: string;
};

@Injectable()
export class LoginService {
  constructor(
    @InjectRepository(PmpSysUserEntity)
    private readonly userRepository: Repository<PmpSysUserEntity>,
    private readonly redisService: RedisService,
    private jwtService: JwtService,
  ) {}
  // 登录
  async login(body: LoginDto): Promise<{
    msg: string;
    code: number;
    data: LoginResponse | string;
  }> {
    try {
      console.log(body);
      const code = await this.redisService.getValue(body.uuid);
      console.log(code);
      if (code === null) {
        return {
          code: 400,
          msg: '验证码过期',
          data: '',
        };
      }

      if (code !== body.code) {
        return {
          code: 400,
          msg: '验证码错误',
          data: '',
        };
      }
      // 验证码验证成功后删除redis key
      await this.redisService.deleteKey(body.uuid);

      const user: PmpSysUserEntity | null = await this.userRepository.findOne({
        where: {
          user_name: body.username,
        },
      });

      if (user === null) {
        return {
          code: 400,
          msg: '账号不存在',
          data: '',
        };
      }

      if (user?.pass_word !== body.password) {
        return {
          code: 400,
          msg: '密码不正确',
          data: '',
        };
      }

      if (user?.status !== 1) {
        return {
          code: 400,
          msg: '账号禁用',
          data: '',
        };
      }

      const token = await this.signIn(user);

      return {
        code: 200,
        msg: '登录成功',
        data: {
          user: user,
          token,
        },
      };
    } catch (e) {
      return {
        code: 500,
        msg: JSON.stringify(e),
        data: '',
      };
    }
  }

  async passLogin(body: PassLoginDto): Promise<{
    msg: string;
    code: number;
    data: LoginResponse | string;
  }> {
    try {
      const user: PmpSysUserEntity | null = await this.userRepository.findOne({
        where: {
          user_name: body.userName,
        },
      });

      if (user === null) {
        return {
          code: 400,
          msg: '账号不存在',
          data: '',
        };
      }

      if (user?.pass_word !== body.passWord) {
        return {
          code: 400,
          msg: '密码不正确',
          data: '',
        };
      }

      if (user?.status !== 1) {
        return {
          code: 400,
          msg: '账号禁用',
          data: '',
        };
      }

      const token = await this.signIn(user);

      return {
        code: 200,
        msg: '登录成功',
        data: {
          user: user,
          token,
        },
      };
    } catch (e) {
      return {
        code: 500,
        msg: JSON.stringify(e),
        data: '',
      };
    }
  }

  // 获取验证码
  async authCode() {
    const captchaData = await this.generateCaptcha();

    return {
      code: 200,
      msg: '操作成功',
      data: captchaData,
    };
  }

  // 封装获取验证码逻辑
  private async generateCaptcha(): Promise<{
    key: string;
    code: string;
  }> {
    const timestr = Date.now();

    const operator =
      CAPTCHA_CONFIG.operators[
        Math.floor(Math.random() * CAPTCHA_CONFIG.operators.length)
      ];

    const { text, data } = captcha.createMathExpr({
      mathMax: CAPTCHA_CONFIG.mathMax,
      mathMin: CAPTCHA_CONFIG.mathMin,
      height: CAPTCHA_CONFIG.height,
      mathOperator: operator,
    });

    // 存入 Redis
    await this.redisService.setPexValue(
      String(timestr),
      text,
      CAPTCHA_CONFIG.ttl,
    );

    console.log('验证码', text);

    return {
      key: String(timestr),
      code: data,
    };
  }

  // token 生成
  async signIn(user: PmpSysUserEntity) {
    const payload = {
      sub: user.id,
      username: user.user_name,
    };
    return await this.jwtService.signAsync(payload);
  }
}
